package com.gba.mark.user.service.permission.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gba.mark.user.entity.permission.Permission;
import com.gba.mark.user.entity.permission.Role;
import com.gba.mark.user.mapper.permission.PermissionMapper;
import com.gba.mark.user.service.permission.IPermissionService;
import com.gba.mark.user.service.permission.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Resource
    private PermissionMapper permissionMapper;

    @Autowired
    private IRoleService sysRoleServiceImpl;

    /**
     * 通过用户ID获取权限
     *
     * @param userId 用户ID
     */
    @Override
    public List<Permission> getPermissionByUserId(Integer userId) {
        //获取用户已有的角色
        List<Role> roles = sysRoleServiceImpl.selectRoleByUserId(userId); //userId = 2733

        List<Permission> permissions = new ArrayList<>();
        roles.stream().forEach((item) -> {
            permissions.addAll(getResourceByRoleId(item.getId()));
        });


        return permissions.stream().distinct().collect(Collectors.toList());
    }

    /**
     * 通过角色获取权限
     */
    @Override
    public List<Permission> getResourceByRoleId(long roleId) {
        return permissionMapper.selectPermissionByRoleId(roleId);
    }

}
